<template>
    <div class="system-container">
  
      <div class="main-content">
        <!-- 左侧订单信息 -->
        <div class="left-panel">
        <div class="section-title">餐台信息</div>
          <div class="table-info">
            <div>餐台编号:{{ currentOrder.table?.tableId }}</div>
            <div>就餐人数:{{ currentOrder.peopleCount }}人</div>
          </div>
          <div class="section-title">订单信息</div>
          <div class="order-info">
            <div>订单ID:{{ currentOrder.orderId }}</div>
          </div>
          <div class="section-title">
            菜品信息
            <el-button 
        type="danger" 
        size="small" 
        @click="clearOrder"
        class="clear-btn"
      >
        <el-icon><Delete /></el-icon>
        清空
      </el-button>
        </div>
          <div class="order-items">
            <div v-for="(item, index) in orderItems" :key="index" class="order-item">
              <div class="item-info">
                <span class="item-name">{{ item.dish.dishName }}</span>
                <span class="item-price">¥{{ item.dish.dishPrice }}</span>
              </div>
              <div class="item-actions">
                <el-button @click="adjustQuantity(item, -1)">-</el-button>
                <span class="quantity">{{ item.quantity }}</span>
                <el-button @click="adjustQuantity(item, 1)">+</el-button>
                <el-button type="text" @click="selectSpec(item)">选规格</el-button>
              </div>
            </div>
          </div>
  

          <div class="order-summary">
            <div class="summary-item">
              <span>订单总价</span>
              <span>¥{{ totalPrice }}</span>
            </div>
            <div class="summary-item discount">
              <span>优惠金额</span>
              <span>-¥{{ discountAmount }}</span>
            </div>
            <div class="summary-item total">
              <span>实付金额</span>
              <span>¥{{ actualPayment }}</span>
            </div>
          </div>
  
          <div class="remarks">
            <el-input
              v-model="remarks"
              type="textarea"
              placeholder="请输入备注"
              rows="2"
            />
          </div>

          <!-- 新增按钮容器 -->
        <div class="order-actions">
          <el-button 
            type="primary" 
            size="large" 
            @click="confirmOrder"
            class="action-button"
            :disabled="isOrderHanged"
          >
            确认下单
          </el-button>
          <el-button 
            type="success" 
            size="large" 
            @click="payOrder"
            class="action-button"
            :disabled="!isOrderConfirmed || isOrderHanged"
          >
            结账
          </el-button>
        </div>
        </div>
  
        <!-- 右侧菜品选择 -->
        <div class="right-panel">
            <!-- 新增头部容器 -->
    <div class="right-header">
            <div class="section-title">点菜区</div>
  
<!-- 操作按钮组 -->
<div class="action-buttons">
        <el-button 
          type="warning" 
          size="small"
          @click="cancelOpening"
        >
          <el-icon><Switch /></el-icon>
          取消开台
        </el-button>
        <el-button 
          :type="isOrderHanged ? 'danger' : 'info'"
          size="small"
          @click="toggleHangOrder"
        >
          <el-icon><Document /></el-icon>
          {{ isOrderHanged ? '取消挂单' : '挂单' }}
        </el-button>
      </div>
    </div>
            <!-- 修改分类标签页为动态生成 -->
  <el-tabs v-model="activeCategory">
    <el-tab-pane 
      v-for="category in categories" 
      :key="category.categoryId"
      :label="category.categoryName" 
      :name="category.categoryName"
    >
      <div class="dish-grid">
        <div 
          v-for="dish in filteredDishes" 
          :key="dish.dishId" 
          class="dish-item"
        >
          <div class="dish-info">
            <div class="dish-name">{{ dish.dishName }}</div>
            <div class="dish-price">¥{{ dish.dishPrice }}</div>
            <div class="dish-status" v-if="dish.dishStatus === '下架'">（已下架）</div>
          </div>
          <el-button 
            @click="addToOrder(dish)"
            :disabled="dish.dishStatus === '下架'"
          >
            + 添加
          </el-button>
        </div>
      </div>
    </el-tab-pane>
  </el-tabs>
                    <!-- 添加分页控件 -->
<!-- 新增分页容器 -->
<div class="pagination-wrapper">
      <div class="pagination-container">
        <el-button icon="arrow-left" circle></el-button>
        <span class="page-info">1/4</span>
        <el-button icon="arrow-right" circle></el-button>
      </div>
    </div>
        </div>

      </div>
  
      <!-- 规格选择对话框 -->
      <el-dialog 
      v-model="specDialogVisible" 
      :title="currentItem?.dish.dishName || '选择规格'"
      width="400px">
        <!-- 规格选择内容 -->
        <!-- <div v-for="spec in currentSpecs" :key="spec">
          <el-radio v-model="selectedSpec" :label="spec">{{ spec }}</el-radio>
        </div> -->
        <div class="spec-options">
    <el-radio-group v-model="selectedTaste">
      <el-radio 
        v-for="taste in currentTastes" 
        :key="taste.tasteId" 
        :label="taste"
        class="spec-option"
      >
        {{ taste.tasteName }}
      </el-radio>
    </el-radio-group>
  </div>
        <template #footer>
          <el-button @click="specDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSpec">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, reactive, onMounted, watch } from 'vue'
  import { Delete, Switch, Document } from '@element-plus/icons-vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
import type { DishDTO } from '@/views/dish/list/types'
import type { CategoryDTO } from '@/views/dish/category/types'
import type { OrderDTO, OrderItemDTO } from '@/views/order/management/types'
import { deleteOrder, getOrderById, updateOrder } from '@/api/order'
import { listAllCategory } from '@/api/category'
import { listAllDish } from '@/api/dish'
import { updateTable } from '@/api/table'
import type { TasteDTO } from '@/views/dish/taste/types'
import { createKitchenTask } from '@/api/kitchen'

  const route = useRoute()
  const orderId = ref(route.params.orderId)
  const router = useRouter()
  
  // 当前订单数据
const currentOrder = ref<OrderDTO>({
  orderId: '',
  table: { tableId: '', tableType: '', tableStatus: '' },
  peopleCount: 0,
  dishes: [],
  orderAmount: 0,
  discountAmount: 0,
  receivedAmount: 0,
  orderTime: '',
  payTime: '',
  orderStatus: '待支付',
  paymentMethod: undefined,
  remarks: ''
})

  const orderItems = ref<OrderItemDTO[]>([])

  // 分类数据
  const categories = ref<CategoryDTO[]>([])
  const activeCategory = ref('') 

  const dishes = ref<DishDTO[]>([])
  
  watch(() => route.params.orderId, async (newOrderId) => {
  if (newOrderId) {
    await loadOrderData(newOrderId as string)
  }
}, { immediate: true })

  const loadOrderData = async (orderId: string) => {
  try {
    // 强制从服务器获取最新数据，不使用缓存
    const orderRes = await getOrderById(orderId)
    
    // 验证订单是否存在
    if (!orderRes.data) {
      ElMessage.error('订单不存在')
      router.push({ name: 'workbench' })
      return
    }
    
    currentOrder.value = orderRes.data
    orderItems.value = currentOrder.value.dishes.map(d => ({
      dish: d.dish,
      quantity: d.quantity,
      note: d.note || ''
    }))
    
    // 加载分类和菜品数据（只加载一次）
    if (categories.value.length === 0) {
      const [categoryRes, dishRes] = await Promise.all([
        listAllCategory(),
        listAllDish()
      ])
      categories.value = categoryRes.data
      dishes.value = dishRes.data
      
      if (categories.value.length > 0) {
        activeCategory.value = categories.value[0].categoryName
      }
    }
  } catch (error) {
    ElMessage.error('加载订单数据失败')
    console.error(error)
    router.push({ name: 'workbench' })
  }
}

// 初始化加载数据
onMounted(async () => {
  // 从路由参数获取订单ID
  // const orderId = route.params.orderId as string
  // if (!orderId) {
  //   ElMessage.error('无效的订单ID')
  //   router.back()
  //   return
  // }

  // try {
  //   // 获取订单数据
  //   const orderRes = await getOrderById(orderId)
  //   currentOrder.value = orderRes.data
    
  //   // 初始化已点菜品
  //   orderItems.value = currentOrder.value.dishes.map(d => ({
  //     dish: d.dish,
  //     quantity: d.quantity,
  //     note: d.note
  //   }))

  //   // 获取所有分类
  //   const categoryRes = await listAllCategory()
  //   categories.value = categoryRes.data
  //   if (categories.value.length > 0) {
  //     activeCategory.value = categories.value[0].categoryName
  //   }

  //   // 获取所有菜品
  //   const dishRes = await listAllDish()
  //   dishes.value = dishRes.data
  // } catch (error) {
  //   ElMessage.error('数据加载失败')
  //   console.error(error)
  // }
loadOrderData(route.params.orderId as string)
})



// 添加分页计算逻辑 按分类过滤菜品
const filteredDishes = computed(() => {
  // const categoryData = dishes.value[activeCategory.value] || []
  // const start = (currentPage.value - 1) * pageSize
  // return categoryData.slice(start, start + pageSize)
  return dishes.value.filter(dish => 
    dish.category === activeCategory.value && 
    dish.dishStatus === '上架'
  )
})

// 添加菜品到订单
const addToOrder = (dish:DishDTO) => {
    const existing = orderItems.value.find(item => item.dish.dishId === dish.dishId)

    if (existing) {
      existing.quantity += 1
    } else {
      orderItems.value.push({
        dish: dish,
        quantity: 1,
        note: ''
      })
    }

      // 更新订单金额
  currentOrder.value.orderAmount = orderItems.value.reduce(
    (sum, item) => sum + (item.dish.dishPrice * item.quantity), 0
  )
  }



  // 计算属性
  const totalPrice = computed(() => 
    orderItems.value.reduce((sum, item) => sum + item.dish.dishPrice * item.quantity, 0)
  )
  
  const discountAmount = computed(() => 0) // 实际应根据优惠规则计算
  const actualPayment = computed(() => totalPrice.value - discountAmount.value)
  
  // 操作逻辑
  const adjustQuantity = (item: { dish: { dishId: number }, quantity: number }, delta: number) => {
    const newQty = item.quantity + delta
     // 当数量减到0时删除该菜品
  if (newQty <= 0) {
    orderItems.value = orderItems.value.filter(
      i => i.dish.dishId !== item.dish.dishId
    )
    return
  }
  item.quantity = newQty

    // 同步更新订单总金额
    currentOrder.value.orderAmount = orderItems.value.reduce(
    (sum, item) => sum + (item.dish.dishPrice * item.quantity), 0
  )
  }
  
// 提交订单
const confirmOrder = async () => {
  try {
    if (orderItems.value.length === 0) {
      ElMessage.warning('请至少添加一个菜品')
      return
    }

    // 更新订单菜品信息
    currentOrder.value.dishes = orderItems.value.map(item => ({
      dish: item.dish,
      quantity: item.quantity,
      note: item.note || ''
    }))

// 计算并更新订单总金额
    currentOrder.value.orderAmount = orderItems.value.reduce(
      (sum, item) => sum + (item.dish.dishPrice * item.quantity), 0
    )

    // 调用更新订单的API
    await updateOrder(currentOrder.value)

    // 创建厨房任务
    const res = await createKitchenTask(currentOrder.value.orderId)
    
    if (res.code === 200) {
      ElMessage.success('订单提交成功，已通知后厨')
      isOrderConfirmed.value = true
      
      // 更新本地订单状态
      currentOrder.value.orderStatus = '待支付'
      
      // 可以在这里添加跳转到后厨界面的逻辑
      // 或者保持当前页面，显示订单已提交的状态
    } else {
      ElMessage.error('创建厨房任务失败: ' + (res.msg || '未知错误'))
    }
  } catch (error) {
    console.error('完整错误信息:', error)
  }
}

//下单状态
const isOrderConfirmed = ref(false)
  // 挂单状态
const isOrderHanged = ref(false)
// 切换挂单状态
const toggleHangOrder = () => {
  isOrderHanged.value = !isOrderHanged.value
  // 这里可以添加挂单状态保存逻辑
  // 挂单时自动保存当前订单状态
  if (isOrderHanged.value) {
    localStorage.setItem('hangedOrder', JSON.stringify(currentOrder.value))
    ElMessage.success('订单已挂起')
    router.push({
      name:'workbench'
    })
  } else {
    localStorage.removeItem('hangedOrder')
    ElMessage.success('已恢复挂起订单')
  }
}

  // 规格选择相关
  const specDialogVisible = ref(false)
  const currentItem = ref<OrderItemDTO | null>(null)
  const selectedTaste = ref<TasteDTO | null>(null)
    const currentTastes = computed(() => {
  return currentItem.value?.dish.tasteOptions || []
})

  const selectSpec = (item: OrderItemDTO) => {
    currentItem.value = item
    selectedTaste.value = item.selectedTaste || null
    specDialogVisible.value = true
  }
  
  const confirmSpec = async () => {
    // currentItem.value.spec = selectedSpec.value
    // specDialogVisible.value = false
  //   if (currentItem.value && selectedTaste.value) {
  //   currentItem.value.selectedTaste = selectedTaste.value
  // }
  // specDialogVisible.value = false
  if (!currentItem.value || !selectedTaste.value) return
  
  // 更新本地数据
  currentItem.value.selectedTaste = selectedTaste.value
  
  // 调用现有接口
  await updateOrder({
    ...currentOrder.value,
    dishes: orderItems.value
  })
  
  specDialogVisible.value = false
  }
  
  // 其他业务逻辑...
  const currentPage = ref(1) // 当前页码
const pageSize = 8 // 每页显示数量



// 清空订单逻辑
const clearOrder = async () => {
  try {
    //清空本地订单项
    orderItems.value = []

    //更新订单数据
    currentOrder.value = {
      ...currentOrder.value,
      dishes: [],
      orderAmount: 0,
      discountAmount: 0,
      receivedAmount: 0
    }
    await updateOrder(currentOrder.value)
    ElMessage.success('已清空当前订单')
  } catch (error) {
    console.error('清空订单失败:', error)
    ElMessage.error('清空订单失败')
  }
}

// 操作方法（需补充业务逻辑）
const cancelOpening = async () => {
  
  try {
    await ElMessageBox.confirm('确定要取消开台并重置桌台状态吗？', '操作确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    console.log('取消开台操作')
    //删除当前订单
    await deleteOrder(currentOrder.value.orderId)
    //更新桌台状态为空闲
    const tableUpdateData = {
      tableId: currentOrder.value.table.tableId,
      tableStatus: '空闲'
    }
    await updateTable(tableUpdateData)
    //跳转回工作台
    router.push({
      name: 'workbench'
    })
    ElMessage.success('已取消开台并重置桌台状态')
  } catch (error) {
    if (error !== 'cancel') {
    console.error('取消开台失败:', error)
    ElMessage.error('取消开台失败，请重试')
    }
  }
}

const payOrder = () => {
    router.push({
      name: 'payment',
      params: {
        orderId: currentOrder.value.orderId
      }
    })
}

  </script>
  
  <style scoped>
  .system-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #f5f5f5;
  }

  .main-content {
    flex: 1;
    display: flex;
    padding: 16px;
    gap: 16px;
  }
  
  .left-panel {
    width: 400px;
    background: white;
    padding: 16px;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 120px);
  }


  /* 右侧面板布局调整 */
.right-panel {
  flex: 1;
  background: white;
  padding: 16px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  position: relative;
}

/* 右侧头部布局 */
.right-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding: 12px 0;
  border-bottom: 2px solid #eee;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
}

.clear-btn {
  margin-right: 8px;
  padding: 6px 10px;
}

.el-button--danger {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.el-button--warning {
  background-color: #E6A23C;
  border-color: #E6A23C;
  color: white;
}

.dish-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }

  .dish-item {
    border: 1px solid #eee;
    padding: 12px;
    border-radius: 4px;
    transition: box-shadow 0.3s;
  }

  .dish-item:hover {
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

/* 分页容器定位 */
.pagination-wrapper {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
}

.pagination-container {
  display: flex;
  align-items: center;
  gap: 15px;
  background: white;
  padding: 8px 20px;
  border-radius: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.order-item {
    padding: 12px 0;
    border-bottom: 1px solid #eee;
  }
  
  .item-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 8px;
  }

  .dish-price, .total span:last-child {
  color: #E6A23C;
  font-weight: bold;
}

/* 禁用状态透明度调整 */
.el-button.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;

  /* 规格选择对话框样式 */
.spec-options {
  padding: 0 20px;
}

.spec-option {
  display: block;
  margin: 12px 0;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s;
}

.spec-option:hover {
  background-color: #f5f7fa;
}

/* 显示已选规格的样式 */
.item-spec {
  margin-left: 8px;
  font-size: 12px;
  color: #888;
}
}

















.el-button--danger:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}




.action-buttons {
  display: flex;
  gap: 8px;
}

/* 按钮样式微调 */
.el-button--warning {
  background-color: #E6A23C;
  border-color: #E6A23C;
  color: white;
}

.el-button--info {
  background-color: #909399;
  border-color: #909399;
  color: white;
}








/* 分页按钮样式 */
.page-info {
  font-size: 14px;
  color: #606266;
  min-width: 50px;
  text-align: center;
}

.el-button.is-circle {
  width: 32px;
  height: 32px;
  padding: 0;
}

.order-actions {
  margin-top: auto; /* 关键布局属性 */
  padding: 16px 0;
  display: flex;
  gap: 20px;
  border-top: 1px solid #eee;
}



/* 调整备注框位置 */
.remarks {
  margin-bottom: 20px;
}

  
  .header {
    display: flex;
    justify-content: space-between;
    padding: 16px;
    background: white;
    border-bottom: 1px solid #eee;
  }







  

  

  
  .footer-actions {
    padding: 16px;
    background: white;
    text-align: right;
  }
  
  .order-summary {
    margin-top: auto;
    padding-top: 16px;
  }
  
  .summary-item {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
  }
  
  .total {
    font-weight: bold;
    color: #ff4444;
  }

  .pagination {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 12px 0;
}

/* 主色调调整 */
.el-button--primary {
  background-color: #67C23A !important; /* 绿色按钮 */
}

/* 订单项规格文字 */
.item-spec {
  color: #888;
  font-size: 12px;
}

/* 菜品价格突出显示 */
.dish-price {
  color: #E6A23C;
  font-weight: bold;
}

/* 输入框边框色 */
.el-textarea__inner {
  border-color: #DCDFE6;
}

/* 清空按钮定位 */
.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

  </style>